import re

from django_redis import get_redis_connection
from redis.client import StrictRedis
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.serializers import ModelSerializer
from rest_framework_jwt.settings import api_settings

from celery_tasks.email.tasks import send_verify_email
from goods.models import SKU
from users.models import User, Address


class CreateUserSerializer(ModelSerializer):
    """注册用户接口的序列化器"""
    password2 = serializers.CharField(label="确认密码", min_length=5, max_length=20, write_only=True)
    sms_code = serializers.CharField(label="验证码", max_length=6, write_only=True)
    allow = serializers.BooleanField(label='同意用户协议', default=False, write_only=True)
    # 生成token序列化字段，需要返回给客户端
    token = serializers.CharField(label='登录状态token', read_only=True)

    def validate_mobile(self, mobile):
        """校验手机号是否合法
        """
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            raise serializers.ValidationError('手机号格式错误')
        return mobile

    def validate_allow(self, value):
        if not value:
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, attrs):
        if attrs.get('password') != attrs.get('password2'):
            raise serializers.ValidationError('两次输入的密码不一致')
        mobile = attrs.get('mobile')
        # 验证码校验
        # 获取StrictRedis对象
        strict_redis = get_redis_connection('sms_codes')  # type: StrictRedis
        # 先查询ｒｅｄｉｓ中是否存在,如果不存在则说明验证码过期
        real_sms_code = strict_redis.get('sms_%s' % mobile)
        if real_sms_code is None:
            raise ValidationError('验证码已过期')

        # 获取用户输入的验证码，校验与生成的是否一致，存在ｒｅｄｉｓ中是字节串，需要解码
        sms_code = attrs.get('sms_code')
        if sms_code != real_sms_code.decode():
            raise ValidationError('验证码不正确')
        return attrs

    def create(self, validated_data):
        """需要自定义字段，如果不自定义，上面创建出来的password2等数据也会往Uesr表中添加，但在表中没有这些字段，就需要重写"""
        # user = User.objects.create(
        user = User.objects.create_user(  # 这个create_user方法会自动给密码加密
            username=validated_data.get('username'),
            password=validated_data.get('password'),
            mobile=validated_data.get('mobile')
        )

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 生payload部分的方法(函数)
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 生成jwt的方法(函数)
        # user：登录的用户对象
        payload = jwt_payload_handler(user)  # 生成payload,  结果是字典类型
        token = jwt_encode_handler(payload)  # 生成jwt字符串
        user.token = token  # 给user添加属性生成的jwt 序列化返回
        return user

    class Meta:
        model = User  # 关联的模型类
        fields = ('id', 'username', 'password', 'mobile',
                  'password2', 'sms_code', 'allow', 'token')
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }


class UserDetailSerializer(ModelSerializer):
    """用于用户详情信息序列化器"""

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class EmailSerialiezr(ModelSerializer):
    """用户修改邮箱的序列化器"""

    def update(self, instance, validated_data):
        # 保存邮箱，序列化器会自动校验邮箱是否合法
        instance.email = validated_data.get('email')
        instance.save()
        # 生成邮箱激活链接
        verify_url = instance.generate_verify_email_url()
        email = validated_data.get('email')
        # （4）发送激活链接到用户邮箱
        # send_verify_email(email, verify_url)
        send_verify_email.delay(email, verify_url)

        return instance

    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email': {
                'required': True
            }
        }


# class UserAddressSerializer(ModelSerializer):
#     """用户地址序列化器: 序列化 + 校验参数"""
#     # 序列化时返回省市区的名称
#     province = serializers.StringRelatedField(read_only=True)
#     city = serializers.StringRelatedField(read_only=True)
#     district = serializers.StringRelatedField(read_only=True)
#
#     # 新增地址时需要传递省市区id
#     province_id = serializers.IntegerField(label='省ID')
#     city_id = serializers.IntegerField(label='市ID')
#     district_id = serializers.IntegerField(label='区ID')
#
#     def validate_mobile(self, value):
#         if not re.match(r'^1[3-9]\d{9}$', value):
#             raise serializers.ValidationError('手机号格式错误')
#         return value
#
#     def create(self, validated_data):
#         validated_data['user'] = self.context['request'].user  # # 获取当前登录用户对象
#         return super().create(validated_data)
#
#     class Meta:
#         model = Address
#         exclude = ('user', 'is_deleted', 'create_time', 'update_time')


class UserAddressSerializer(ModelSerializer):
    """地址管理的序列化器"""

    # 需求: 序列时,返回省市区的名称, 而不是默认返回主键id
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)

    # 新增三个属性: 新地址时用到
    province_id = serializers.IntegerField(label='省ID')
    city_id = serializers.IntegerField(label='市ID')
    district_id = serializers.IntegerField(label='区ID')

    def create(self, validated_data):
        # 在新增一条地址数据时, 需要自动设置user字段, 因为用户没有传递此字段给服务器
        validated_data['user'] = self.context.get('request').user

        return super().create(validated_data)  # 新增一条地址数据
        # Address.objects.create(receiver=xx, title=xx, province_id=xx, city_id=xx..)

    class Meta:
        model = Address
        # fields = ('id',)
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')


class AddBrowseHistorySerializer(serializers.Serializer):
    """
    添加用户浏览历史序列化器
    """
    sku_id = serializers.IntegerField(label="商品SKU编号", min_value=1)

    def validate_sku_id(self, value):
        """
        检验sku_id是否存在
        """
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')
        return value

    def create(self, validated_data):
        """
        保存
        """
        # 序列化器用于GenericAPIView时，会有一个字典类型的属性叫context，里面包含了request对象
        user_id = self.context.get('request').user.id
        sku_id = validated_data['sku_id']

        redis_conn = get_redis_connection("history")  # type: StrictRedis

        # 移除已经存在的本商品浏览记录
        redis_conn.lrem("history_%s" % user_id, 0, sku_id)
        # 添加新的浏览记录
        redis_conn.lpush("history_%s" % user_id, sku_id)
        # 只保存最多5条记录
        redis_conn.ltrim("history_%s" % user_id, 0, 4)

        return validated_data
